package com.zds.support.util

import android.os.StatFs
import android.webkit.MimeTypeMap
import java.io.File
import java.math.BigDecimal

object FileUtils {


    @JvmStatic
    fun getMimeType(url: String): String {

        val extension: String? = MimeTypeMap.getFileExtensionFromUrl(url)
        if (extension != null) {
            try {
                val mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
                if (mime != null) {
                    return mime
                }
            } catch (e: Exception) {

            }

        }

        return ""
    }

    // 格式化单位
    @JvmStatic
    fun getFormatSize(size: Long): String {
        val kiloByte = size / 1024.0

        val megaByte = kiloByte / 1024.0
        if (megaByte < 1) {
            val result1 = BigDecimal(kiloByte.toString())
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB"
        }
        val gigaByte = megaByte / 1024.0
        if (gigaByte < 1) {
            val result2 = BigDecimal(megaByte.toString())
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB"
        }
        val teraBytes = gigaByte / 1024.0
        if (teraBytes < 1) {
            val result3 = BigDecimal(gigaByte.toString())
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB"
        }
        val result4 = BigDecimal(teraBytes)
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB"
    }

    // 获取指定文件夹内所有文件大小的和
    @JvmStatic
    fun getFolderSize(file: File): Long {
        var size: Long = 0
        try {
            val fileList = file.listFiles()
            if (fileList!=null){
                for (aFileList in fileList) {
                    if (aFileList!=null){
                        if (aFileList.isDirectory) {
                            size = size + getFolderSize(aFileList)
                        } else {
                            size = size + aFileList.length()
                        }
                    }

                }
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }

        return size
    }

    /**
     * 获取可用存储空间大小
     */
    @JvmStatic
    fun getAvailableBytes(path: String): Long {
        val statFs = StatFs(path)
        val availableBytes = statFs.availableBytes
        return availableBytes
    }
}